if exists (select * from sys.sysobjects where xtype='p' and id=OBJECT_ID('usp_ShopcartBatch'))
begin
	drop proc [usp_ShopcartBatch]
end

go

IF TYPE_ID(N'ShopcartTableType') IS NOT NULL
DROP TYPE ShopcartTableType
GO


CREATE TYPE [dbo].[ShopcartTableType] AS TABLE(
	[CartID] [uniqueidentifier] NOT NULL,
	[ProductID] [uniqueidentifier] NULL,
	[CustomerID] [uniqueidentifier] NULL,
	[ProductCode] [varchar](50) NULL,
	[Quantity] [decimal](18,4) NULL,
	[Unit] [varchar](10) NULL,
	[BatchCode] [varchar](50) NULL,
	[DueDate] [date] NULL,
	[Inventory] [decimal](18, 4) NULL,
	[Remark] [varchar](100) NULL,
	[CreatedAt] [datetime] NULL,
	[Deleted] [bit] NULL
)
GO 

CREATE PROCEDURE [dbo].[usp_ShopcartBatch]
	@DataTable dbo.[ShopcartTableType] readonly,
	@OpType int -- 0:insert,1:Update 
AS

IF @OpType = 0
BEGIN
	INSERT INTO dbo.Biz_ShopCart
	SELECT NEWID(),ProductID,CustomerID,ProductCode,Quantity,Unit,BatchCode,DueDate,Inventory,Remark,GETDATE(),0
	FROM @DataTable
END

IF @OpType = 1
BEGIN
	UPDATE A SET 
	Quantity=B.Quantity
	,Unit=B.Unit 
	,ProductCode = C.ProductCode
	,Remark = B.Remark
	FROM Biz_ShopCart A JOIN @DataTable B
	ON A.CartID = B.CartID
	JOIN Bas_Product C ON A.ProductID =C.ProductID
END


GO

